package iv1201project.extras;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * A bean validator for the availability.
 */
public class AvailabilityValidator implements Validator {
    /**
     * Checks that fields are correctly filled, else notifies the user.
     * @param context Context information.
     * @param component Contains information about the component which is validated.
     * @param value Contains the value the user put in the field.
     * @throws ValidatorException 
     */
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String id = component.getId();

        if (id.equalsIgnoreCase("from")) {
            String enteredValue = (String) value;
            DateFormat format = new SimpleDateFormat("yyyy-mm-dd");
            try {
                format.parse(enteredValue);
            } catch (ParseException ex) {
                notifyClient("Please enter a valid date!");
            }
        }
        if (id.equalsIgnoreCase("to")) {
            String enteredValue = (String) value;
            DateFormat format = new SimpleDateFormat("yyyy-mm-dd");
            try {
                format.parse(enteredValue);
            } catch (ParseException ex) {
                notifyClient("Please enter a valid date!");
            }
        }      
    }

    /**
     * Notifies a client with an html message.
     * @param msg The message with which to notify cliend
     * @throws ValidatorException Thrown when the validation fails.
     */
    private void notifyClient(String msg) throws ValidatorException {
        FacesMessage message = new FacesMessage();
        message.setSummary(msg);
        throw new ValidatorException(message);
    }
}
